# @Author   : tan90
# @Time     : 2025/1/25 08:44

import socket


# 创建 TCP 套接字
def create_tcp_socket(ip, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((ip, port))
    sock.listen(5)
    print(f"TCP 服务器已启动，监听 {ip}:{port}")
    return sock


# 接受客户端连接
def accept_client(sock):
    print("等待客户端连接...")
    client_sock, client_addr = sock.accept()
    print(f"客户端已连接: {client_addr}")
    return client_sock, client_addr


# 与客户端通信
def handle_client(client_sock):
    while True:
        data = client_sock.recv(1024)
        if not data:
            break
        print(f"收到数据: {data.decode()}")
        client_sock.send(b"Received: " + data)
    client_sock.close()
    print("客户端已断开连接")


if __name__ == '__main__':
    # 创建 TCP 套接字
    sock = create_tcp_socket('0.0.0.0', 54321)
    # 接受客户端连接并处理
    while True:
        client_sock, client_addr = accept_client(sock)
        handle_client(client_sock)
